package com.wechat.controller;

import com.wechat.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.http.HttpStatus;

@RestController
@RequestMapping("/api/questions")
public class QuestionController {
    @Autowired
    private QuestionService questionService;

    @GetMapping
    public List<Map<String, Object>> listQuestions() {
        return questionService.listQuestions();
    }

    @GetMapping("/{id}")
    public Map<String, Object> getQuestion(@PathVariable Long id) {
        Map<String, Object> result = questionService.getQuestionDetail(id);
        if (result == null || result.get("question") == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "问题不存在");
        }
        return result;
    }

    @PostMapping("/{id}/answers")
    public void addAnswer(@PathVariable Long id, @RequestBody Map<String, String> body) {
        Long userId = Long.valueOf(body.getOrDefault("userId", "1"));
        questionService.addAnswer(id, body.get("content"), userId);
    }

    @PostMapping
    public Map<String, Object> addQuestion(@RequestBody Map<String, String> body,
            @RequestHeader("Authorization") String token) {
        Long userId = com.wechat.util.JwtUtil.getUserId(token);
        String title = body.get("title");
        String content = body.get("content");
        com.wechat.entity.Question question = new com.wechat.entity.Question();
        question.setTitle(title);
        question.setContent(content);
        question.setUserId(userId);
        question.setViewCount(0);
        question.setAnswerCount(0);
        question.setCreatedAt(new java.sql.Timestamp(System.currentTimeMillis()));
        questionService.addQuestion(question);
        Map<String, Object> res = new java.util.HashMap<>();
        res.put("msg", "发布成功");
        return res;
    }
}